#include <QVBoxLayout>
#include <QMessageBox>
#include <QFileDialog>
#include <QRegularExpression>

#include "TabPage_lines.h"
#include "Style_lines.h"


using namespace std;
void TabPage_lines::fillData(ConfigUI* conf) {
	// 解析并填充数据
	m_dataAcquired = m_parser->readFile(m_qFullName);
	if (!m_dataAcquired) return;
	m_runFinished = false;
	// 创建Diagram
	shared_ptr<DiagramData> diagramData = std::static_pointer_cast<DiagramData>(
		std::shared_ptr<Data_lines>(m_data, [](auto*) {})); // 共享指针但不删除
	// 创建配置（需要实现Config类）
	m_config = conf;
	m_diagram = new Diagram(diagramData, m_config, this);
	m_algm = new AlgorithmLink_lines(m_data, m_config);
	// 设置布局
	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(m_diagram);
	setLayout(layout);
}
void TabPage_lines::refreshUI() {
	m_diagram->refresh();
};
// 槽函数
void TabPage_lines::onConfigChanged() { 
	refreshUI();
}
void TabPage_lines::tranformChanged() {
	m_diagram->initViewTransform();
	refreshUI();
}
void TabPage_lines::action_save_case() {
	m_qFullSaveName = QFileDialog::getSaveFileName(this,
		tr("保存json文件"),
		m_qFilePath,  // 拼接默认文件名 + "/" + defaltName
		tr("map files (*.map)")
	);
	bool saved = m_parser->saveFile(m_qFullSaveName);
	if (saved)
		QMessageBox::information(this, tr("提示: "), tr("保存成功!"));
	else
		QMessageBox::warning(this, tr("警告: "), tr("保存失败!"));
}
void TabPage_lines::leftPressRun(SelectedTarget* target) {
	if (target->lineSelected) {
		m_algm->pushLineRunBegin(target->sLine, *target->linesToRun);
	}
	else if (target->pinSelected) {
		m_algm->pushPinRunBegin(target->nearistPt, *target->linesToRun);
	}
}
void TabPage_lines::leftPressMoveRun(SelectedTarget* target){
	if (target->lineSelected) {
		m_algm->pushLineRun(target->offset, false, m_config->m_postOn);
	}
	else if (target->pinSelected) {
		m_algm->pushPinRun(target->offset, false);
	}
}
void TabPage_lines::leftReleaseRun(SelectedTarget* target) {
	if (target->lineSelected) {
		m_algm->pushLineRun(target->offset, m_config->m_onGrids, m_config->m_postOn);
	}
	else if (target->pinSelected) {
		m_algm->pushPinRun(target->offset, m_config->m_onGrids);
	}
}
